
import { Navigate, useRoutes } from "react-router-dom"
import { lazy, Suspense } from "react"
import Loading from "../components/loading"
/*
路由懒加载
React.lazy 函数能让你像渲染常规组件一样处理动态引入的组件。
React.lazy 接受一个函数，这个函数需要动态调用 import()
然后应在 Suspense 组件中渲染 lazy 组件，如此使得我们可以使用在等待加载 lazy 组件时做优雅降级（如 loading 指示器等）*/
const Login = lazy(() => import("../pages/Login"))
const Main = lazy(() => import("../pages/Main"))
const NotFound = lazy(() => import("../components/404"))
const About = lazy(() => import("../pages/Main/About"))
const Home = lazy(() => import("../pages/Main/Home"))
const List = lazy(() => import("../components/List"))
const load = (Comp) => {
    return (
        <Suspense fallback={ <Loading/>}>
            <Comp />
        </Suspense>
    )
}

const routes = [
    {
        path: '/login',
        element: load(Login)
    }, {
        path: '/main',
        element: load(Main),
        children: [
            {
                path: '/main/home',
                element: load(Home),
                children: [
                    {
                        path: '/main/home/music/:id',
                        element: load(List)
                    }, {
                        path: '/main/home/news/:id',
                        element: load(List)
                    }
                ]
            }, {
                path: '/main/about',
                element: load(About)
            }
        ]
    }, {
        path: '/',
        element: <Navigate to="/login" />
    }, {
        path: '*',
        element: load(NotFound)
    }
]
export default routes;
//这样的写法,认为定义了 GetRoutes 组件 这个组件就是根据路由表生成的 路由配置结构
export const GetRoutes = () => {
    //在组件中在外层可以使用hook
    return useRoutes(routes)
}
//自定义hooks
export const useMyRoutes = () => {
    //在自定义hooks中是可以使用hook
    return useRoutes(routes)
}
